import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import type { CalendarEvent, UserActivity, CreateEventRequest, UpdateEventRequest } from '@/types/calendar'
import * as calendarApi from '@/api/calendar'

export const useCalendarStore = defineStore('calendar', () => {
  // 状态
  const events = ref<CalendarEvent[]>([])
  const activities = ref<UserActivity[]>([])
  const activityStats = ref<{
    totalActivities: number
    streakDays: number
    thisWeekActivities: number
    thisMonthActivities: number
  }>({ totalActivities: 0, streakDays: 0, thisWeekActivities: 0, thisMonthActivities: 0 })
  const isLoading = ref(false)
  const selectedDate = ref<string>(new Date().toISOString().split('T')[0])

  // 计算属性
  const todayEvents = computed(() => {
    const today = new Date().toISOString().split('T')[0]
    return events.value.filter(event => 
event.date.toString() === today
    ).sort((a, b) => {
      if (!a.time && !b.time) return 0
      if (!a.time) return 1
      if (!b.time) return -1
      return a.time.localeCompare(b.time)
    })
  })

  const selectedDateEvents = computed(() => {
    return events.value.filter(event => 
event.date.toString() === selectedDate.value
    ).sort((a, b) => {
      if (!a.time && !b.time) return 0
      if (!a.time) return 1
      if (!b.time) return -1
      return a.time.localeCompare(b.time)
    })
  })

  const upcomingEvents = computed(() => {
    const today = new Date()
    const nextWeek = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
    const todayStr = today.toISOString().split('T')[0]
    const nextWeekStr = nextWeek.toISOString().split('T')[0]
    
    return events.value.filter(event => 
      event.date.toString() >= todayStr && event.date.toString() <= nextWeekStr
    ).sort((a, b) => {
      const dateCompare = a.date.toString().localeCompare(b.date.toString())
      if (dateCompare === 0) {
        return (a.time || '').localeCompare(b.time || '')
      }
      return dateCompare
    })
  })

  const recentActivities = computed(() => {
    return activities.value
      .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
      .slice(0, 10)
  })

  // 获取日历事件
  const fetchEvents = async () => {
    const now = new Date()
    return fetchEventsByMonth(now.getFullYear(), now.getMonth() + 1)
  }

  const fetchEventsByMonth = async (year: number, month: number) => {
    try {
      isLoading.value = true
      const response = await calendarApi.getCalendarEvents({ year, month })
      
      if (response.success && response.data) {
        events.value = response.data
      }
    } catch (error) {
      console.error('Failed to fetch events:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取指定月份的事件（删除重复定义）

  // 创建日历事件
  const createEvent = async (data: CreateEventRequest) => {
    try {
      isLoading.value = true
      const response = await calendarApi.createEvent(data)
      
      if (response.success && response.data) {
        events.value.push(response.data)
        return response.data
      }
    } catch (error) {
      console.error('Failed to create event:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 更新日历事件
  const updateEvent = async (id: number, data: UpdateEventRequest) => {
    try {
      isLoading.value = true
      const response = await calendarApi.updateEvent(id, data)
      
      if (response.success && response.data) {
        const index = events.value.findIndex(event => Number(event.id) === id)
        if (index !== -1) {
          events.value[index] = response.data
        }
        return response.data
      }
    } catch (error) {
      console.error('Failed to update event:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 删除日历事件
  const deleteEvent = async (id: number) => {
    try {
      isLoading.value = true
      await calendarApi.deleteEvent(id)
      
      events.value = events.value.filter(event => Number(event.id) !== id)
    } catch (error) {
      console.error('Failed to delete event:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取即将发生的事件
  const fetchUpcomingEvents = async (days: number = 7) => {
    try {
      isLoading.value = true
      const response = await calendarApi.getUpcomingEvents(days)
      
      if (response.success && response.data) {
        // 更新事件列表中的即将发生的事件
        const upcomingEventIds = response.data.map(e => e.id)
        events.value = events.value.filter(e => !upcomingEventIds.includes(e.id))
        events.value.push(...response.data)
        
        return response.data
      }
    } catch (error) {
      console.error('Failed to fetch upcoming events:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取活动热力图数据
  const fetchActivityHeatmap = async (year?: number) => {
    try {
      isLoading.value = true
      const response = await calendarApi.getActivityHeatmap(year)
      
      if (response.success && response.data) {
        // @ts-ignore
        activities.value = response.data
        return response.data
      }
    } catch (error) {
      console.error('Failed to fetch activity heatmap:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取最近活动
  const fetchRecentActivities = async (limit: number = 10) => {
    try {
      isLoading.value = true
      const response = await calendarApi.getRecentActivities(limit)
      
      if (response.success && response.data) {
        activities.value = response.data
        return response.data
      }
    } catch (error) {
      console.error('Failed to fetch recent activities:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取活动统计
  const fetchActivityStats = async () => {
    try {
      isLoading.value = true
      const response = await calendarApi.getActivityStats()
      
      if (response.success && response.data) {
        // @ts-ignore
        activityStats.value = response.data
        return response.data
      }
    } catch (error) {
      console.error('Failed to fetch activity stats:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 记录活动
  const recordActivity = async (data?: { date?: string; count?: number }) => {
    try {
      const response = await calendarApi.recordActivity(data)
      
      if (response.success && response.data) {
        // 更新活动列表
        const existingIndex = activities.value.findIndex(
          activity => activity.date === response.data!.date
        )
        
        if (existingIndex !== -1) {
          // @ts-ignore
          activities.value[existingIndex] = response.data
        } else {
          // @ts-ignore
          activities.value.unshift(response.data)
        }
        
        // 更新统计数据
        activityStats.value.totalActivities += 1
        
        return response.data
      }
    } catch (error) {
      console.error('Failed to record activity:', error)
      throw error
    }
  }

  // 设置选中的日期
  const setSelectedDate = (date: string) => {
    selectedDate.value = date
  }

  // 获取指定日期的活动数量
  const getActivityCountForDate = (date: string) => {
    const activity = activities.value.find(a => a.date.toString() === date)
    return activity ? activity.count : 0
  }

  // 检查指定日期是否有事件
  const hasEventsOnDate = (date: string) => {
    return events.value.some(event => event.date.toString() === date)
  }

  // 获取指定日期的事件
  const getEventsForDate = (date: string) => {
    return events.value.filter(event => event.date.toString() === date)
  }

  return {
    // 状态
    events: readonly(events),
    activities: readonly(activities),
    activityStats: readonly(activityStats),
    isLoading: readonly(isLoading),
    selectedDate: readonly(selectedDate),
    
    // 计算属性
    todayEvents,
    selectedDateEvents,
    upcomingEvents,
    recentActivities,
    
    // 方法
    fetchEvents,
    fetchEventsByMonth,
    createEvent,
    updateEvent,
    deleteEvent,
    fetchUpcomingEvents,
    fetchActivityHeatmap,
    fetchRecentActivities,
    fetchActivityStats,
    recordActivity,
    setSelectedDate,
    getActivityCountForDate,
    hasEventsOnDate,
    getEventsForDate
  }
})